package dao

import (
	"go-admin1/admin/system/model"
	"go-admin1/internal/infrastructure/database"
	"go-admin1/internal/infrastructure/logger"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// SysDeptDao 部门数据访问接口
type SysDeptDao interface {
	Create(dept *model.SysDept) error
	GetByID(id int64) (*model.SysDept, error)
	Update(dept *model.SysDept) error
	Delete(id int64) error
	List(page, pageSize int) ([]*model.SysDept, int64, error)
	ListByParentID(parentID int64) ([]*model.SysDept, error)
}

type sysDeptDao struct {
	db *gorm.DB
}

// NewSysDeptDao 创建部门数据访问实例

// NewSysConfigDao 创建配置参数数据访问实例
func NewSysDeptDao() SysDeptDao {
	return &sysDeptDao{
		db: database.GetDB(),
	}
}

func (d *sysDeptDao) Create(dept *model.SysDept) error {
	logger.Info("创建部门", zap.Int64("dept_id", dept.DeptID))
	return d.db.Create(dept).Error
}

func (d *sysDeptDao) GetByID(id int64) (*model.SysDept, error) {
	logger.Debug("根据ID获取部门", zap.Int64("dept_id", id))
	var dept model.SysDept
	err := d.db.Where("dept_id = ? AND del_flag = '0'", id).First(&dept).Error
	return &dept, err
}

func (d *sysDeptDao) Update(dept *model.SysDept) error {
	logger.Info("更新部门", zap.Int64("dept_id", dept.DeptID))
	return d.db.Save(dept).Error
}

func (d *sysDeptDao) Delete(id int64) error {
	logger.Info("删除部门", zap.Int64("dept_id", id))
	return d.db.Where("dept_id = ?", id).Delete(&model.SysDept{}).Error
}

func (d *sysDeptDao) List(page, pageSize int) ([]*model.SysDept, int64, error) {
	logger.Debug("获取部门列表")
	var depts []*model.SysDept
	var total int64
	offset := (page - 1) * pageSize
	db := d.db.Model(&model.SysDept{})

	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if err := db.Offset(offset).Limit(pageSize).Find(&depts).Error; err != nil {
		return nil, 0, err
	}

	return depts, total, nil
}

func (d *sysDeptDao) ListByParentID(parentID int64) ([]*model.SysDept, error) {
	logger.Debug("根据父ID获取部门列表", zap.Int64("parent_id", parentID))
	var depts []*model.SysDept
	err := d.db.Where("parent_id = ? AND del_flag = '0'", parentID).Find(&depts).Error
	return depts, err
}
